package com.sky.directdeal.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.android.gms.maps.model.LatLng;
import com.sky.directdeal.R;
import com.sky.directdeal.listener.ServiceResponseListener;
import com.sky.directdeal.manager.ServiceManager;
import com.sky.directdeal.manager.SharedPreferenceManager;
import com.sky.local_ads.localitylist.LocalityList;
import com.sky.local_ads.localitylist.LocalityResponse;

public class UserLocationActivity extends BaseActivity {
	private boolean isService=false;
	private TextView geoCoderLocText;
	private AutoCompleteTextView locSearchText;
	//private GoogleMap googleMap;
	//private SupportMapFragment mapFragment;
	private Button setLocationButton;
	private ArrayList<String> localityList=new ArrayList<String>();
	
	private ListView localityListView;
	
	private ProgressBar localityListProgresBar;
	
	private List<LocalityList> localitySearchResponseList;
	
	private List<LocalityList> localityListResponseList;
	@Override
	protected void onCreate(Bundle savedInstanceState) { 
		//getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
		super.onCreate(savedInstanceState);
		setHeaderTitle(getResources().getString(R.string.location_setting));
		setContentView(R.layout.activity_user_location);
		initUI();
		
		/*LocationAddress locationAddress=LocationProvider.getInstance().getLocationAddress();
		if(locationAddress!=null){
			Log.e("loc", locationAddress.getLatLng().latitude+"");
		}
		
		if(!isService){
			isService=true;
			mainCategoryHandler.sendEmptyMessage(Constants.SHOW_PROGRESS_DIALOG);
			GeoCoder geoCoder=new GeoCoder(this, new AddressStatusListener() {
				
				@Override
				public void startProgress() {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void onSuccess(LocationAddress locationAddress) {
					isService=false;
					mainCategoryHandler.sendEmptyMessage(Constants.DISMISS_PROGRESS_DIALOG);
					String location=null;
					if(locationAddress.getSubLocality1()!=null)
						location=locationAddress.getSubLocality1();
					if(locationAddress.getSubLocality2()!=null)
						location=location+","+locationAddress.getSubLocality2();
					geoCoderLocText.setText(location);
					addMarker(locationAddress.getLatLng());
					
				}
				
				@Override
				public void onFailure() {
					isService=false;
					mainCategoryHandler.sendEmptyMessage(Constants.DISMISS_PROGRESS_DIALOG);
					
				}
				
				@Override
				public void gpsNotRequired() {
					// TODO Auto-generated method stub
					
				}
			});
			geoCoder.getAddress(null);
		}*/
	}
	
	private void initUI(){
		/*FragmentManager fm = getSupportFragmentManager();
		mapFragment = (SupportMapFragment) fm.findFragmentById(R.id.map);
		googleMap = mapFragment.getMap();
		googleMap.getUiSettings().setZoomControlsEnabled(false);*/
		geoCoderLocText=(TextView)findViewById(R.id.geoCoderLocation);
		localityListView=(ListView)findViewById(R.id.listViewLocality);
		localityListView.setOnItemClickListener(localityListClickListener);
		localityListProgresBar=(ProgressBar)findViewById(R.id.progressBarLocality);
		locSearchText=(AutoCompleteTextView)findViewById(R.id.locationTextView);
		locSearchText.addTextChangedListener(locaTextWatcher);
		locSearchText.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				String localitySting=(String)arg0.getAdapter().getItem(arg2);
				int localityId=localitySearchResponseList.get(arg2).getLocalityId();
				saveLocality(localitySting,localityId);
			}
		});
		setLocationButton=(Button)findViewById(R.id.buttonSetLocation);
		setLocationButton.setOnClickListener(setLocButtonListener);
		loadLocalityList();
		String locatlity=getLocaltiy();
		if(locatlity!=null){
			locSearchText.setText(locatlity);
		}
		
	}

	private OnClickListener setLocButtonListener=new OnClickListener() {
		
		@Override
		public void onClick(View arg0) {
			Intent homeActivity = new Intent(UserLocationActivity.this,
                    HomeActivity.class);

            startActivity(homeActivity);
            finish();
		}
	};
	
	private TextWatcher locaTextWatcher=new TextWatcher() {
		
		@Override
		public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
			if(arg0.length()>0){
				searchLocality(arg0.toString());
			}
			
		}
		
		@Override
		public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {
			
		}
		
		@Override
		public void afterTextChanged(Editable arg0) {
			// TODO Auto-generated method stub
			
		}
	};
	
	private void searchLocality(String keyword){
		if(checkInternet(true)){
			ServiceManager.getLocalityByKeyword(UserLocationActivity. this, keyword, locSearchListener);
		}
	}
	
	private ServiceResponseListener<LocalityResponse> locSearchListener=new ServiceResponseListener<LocalityResponse>() {
		
		@Override
		public void onSuccess(LocalityResponse response) {
			isService=false;
			if(response!=null&& response.getLocalityList()!=null){
				localityList.clear();
				localitySearchResponseList=response.getLocalityList();
				int locSize=localitySearchResponseList.size();
				for(int i=0;i<locSize;i++){
					localityList.add(localitySearchResponseList.get(i).getLocalityName());
				}
				ArrayAdapter<String> adapter=new ArrayAdapter<String>(UserLocationActivity.this, android.R.layout.simple_dropdown_item_1line,localityList);
				locSearchText.setAdapter(adapter);
				
			}
			
		}
		
		@Override
		public void onFailure(Throwable throwable, String errorResponse) {
			isService=false;
			
		}
	};
	
	private ServiceResponseListener<LocalityResponse> locListListener=new ServiceResponseListener<LocalityResponse>() {
		
		@Override
		public void onSuccess(LocalityResponse response) {
			isService=false;
			if(response!=null&& response.getLocalityList()!=null){
				localityListResponseList=response.getLocalityList();
				int locSize=localityListResponseList.size();
				ArrayList<String> localityList=new ArrayList<String>();
				for(int i=0;i<locSize;i++){
					localityList.add(localityListResponseList.get(i).getLocalityName());
				}
				ArrayAdapter<String> adapter=new ArrayAdapter<String>(UserLocationActivity.this, android.R.layout.simple_list_item_1,localityList);
				localityListView.setAdapter(adapter);
				
			}
			localityListProgresBar.setVisibility(View.GONE);
			localityListView.setVisibility(View.VISIBLE);
		}
		
		@Override
		public void onFailure(Throwable throwable, String errorResponse) {
			isService=false;
			localityListProgresBar.setVisibility(View.GONE);
			showAlert(UserLocationActivity.this, getString(R.string.server_failed), getString(R.string.server_unavailable), getString(R.string.ok_button), positiveListener, null, null);
			
			
		}
	};
	
public DialogInterface.OnClickListener positiveListener=new DialogInterface.OnClickListener() {
		
		@Override
		public void onClick(DialogInterface dialog, int which) {
			finish();
		}
	};
	
	private void addMarker(LatLng latlng){/*

		MarkerOptions markerOptions = new MarkerOptions();
		markerOptions.position(latlng);
		markerOptions.title("Current Location");
		googleMap.addMarker(markerOptions);
		CameraUpdate updatePosition = CameraUpdateFactory
				.newLatLng(latlng);
		CameraUpdate updateZoom = CameraUpdateFactory.zoomTo(14);
		googleMap.moveCamera(updatePosition);
		googleMap.animateCamera(updateZoom);
	*/}
	
	private void loadLocalityList(){
		if(checkInternet(true) && !isService){
		   localityListProgresBar.setVisibility(View.VISIBLE);	
			ServiceManager.getLocalityList(UserLocationActivity.this, locListListener);
		}
	}
	
	private OnItemClickListener localityListClickListener=new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			String localitySting=(String)arg0.getAdapter().getItem(arg2);
			int localityId=localityListResponseList.get(arg2).getLocalityId();
			saveLocality(localitySting,localityId);			
		}
	};
	
	private void saveLocality(String locality,int localityId){
		if(locality!=null){
			SharedPreferenceManager.savePreferences(UserLocationActivity.this, SharedPreferenceManager.Keys.PREFERRED_LOCATION,locality );	
			SharedPreferenceManager.savePreferences(UserLocationActivity.this, SharedPreferenceManager.Keys.PREFERRED_LOCATION_ID, localityId);
			SharedPreferenceManager.savePreferences(this, SharedPreferenceManager.Keys.IS_LOC_CONFIGURED, true);
			Intent homeActivity = new Intent(UserLocationActivity.this,
                    HomeActivity.class);

            startActivity(homeActivity);
            finish();
		}
	}
	
	private String getLocaltiy(){
		String locality=SharedPreferenceManager.getPreferenceStringValue(UserLocationActivity.this, SharedPreferenceManager.Keys.PREFERRED_LOCATION);
		return locality;
	}
}
